<template>
    <div>
        <el-dialog :title="title" v-model="props.showPayment" width="600px" @close="handleClose">
            <el-form ref="payMentRef" :model="form" :rules="rules" label-width="auto" label-position="left"
                v-if="proxy.typeIndex != 1">
                <el-form-item label="自定义" prop="allCountries" required>
                    <el-radio-group v-model="form.allCountries" @change="customization">
                        <el-radio :value="true" size="large">所有国家</el-radio>
                        <el-radio :value="false" size="large">自定义国家</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="支持区域" prop="CountryLineList" :required="!form.allCountries">
                    <el-tree-select multiple v-model="form.CountryLineList" placeholder="请选择" :data="sys_country"
                        :props="defaultProps" :disabled="form.allCountries">
                    </el-tree-select>
                </el-form-item>
                <el-form-item label="当前环境" prop="environment" required>
                    <el-select v-model="form.environment" placeholder="请选择">
                        <el-option v-for="item in sys_pay_env" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="支付标识" prop="paymentMethodCode" required>
                    <el-select v-model="form.paymentMethodCode" placeholder="请选择">
                        <el-option v-for="item in payment_way_type" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="支付状态" prop="status" required>
                    <el-select v-model="form.status" placeholder="请选择">
                        <el-option v-for="item in statusList" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="图标" prop="newImage" required>
                    <image-upload @baseUrl="handleBaseUrl" v-model="form.newImage" :limit="1" />
                </el-form-item>
                <el-form-item prop="paymentWayDescriptionList">
                    <MoreLanguage :newList="form.paymentWayDescriptionList" label="支付名称" @publicCheck="publicCheck">
                    </MoreLanguage>
                </el-form-item>
            </el-form>
            <el-table :data="parametersList" v-if="proxy.typeIndex == 1">
                <el-table-column label="KEY">
                    <template #default="scope">
                        <el-input placeholder="请输入" v-model="scope.row.paymentKey" />
                    </template>
                </el-table-column>
                <el-table-column label="值">
                    <template #default="scope">
                        <el-input placeholder="请输入" v-model="scope.row.paymentValue" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="70">
                    <template #default="scope">
                        <el-button type="danger" :icon="Delete" circle @click="handleDelete(scope.$index, scope.row)" />
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <el-button type="primary" @click="handleAddBrandDescription"
                    :style="proxy.typeIndex === 1 ? styleObject : ''">添加</el-button>
                <el-button type="danger" @click="handleDeleteBrandDescription" style="margin-right: 270px"
                    v-if="props.typeIndex != 1">删除</el-button>
                <el-button type="primary" @click="handleSure">{{ proxy.typeIndex != 1 ? "确 定" : "保 存" }}</el-button>
                <el-button @click="handleClose">取 消</el-button>
            </template>
        </el-dialog>

    </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, watch, reactive } from "vue";
import {
    Delete
} from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance();
const { sys_pay_env, payment_way_type } = proxy.useDict("sys_pay_env","payment_way_type");
const emits = defineEmits(["handleSure", "handleClose"]);
const sys_country = ref([]); // 国家
const sys_language_type = ref([]); // 语言
const checkedBrandDescription = ref([]); // 语言
const parametersList = ref([])//支付参数列表
const styleObject = {
    marginRight: "350px"
}
const props = defineProps({
    publicItem: {
        type: Object,
        default: {},
    },
    showPayment: {
        type: Boolean,
        default: false,
    },
    typeIndex: {
        type: Number,
        default: null, //1是参数2是编辑3是新增
    },
});
const title = ref('新增')
const form = ref({
    environment: '', //环境
    status: 1,//状态 
    newImage: "",
    iconImage: '',//图标
    paymentWayDescriptionList: [],//多语言
    CountryLineList: [],//支持区域--自定义
    paymentWayCountryLineList: [],//支持区域
    allCountries: false,//默认是不支持所有国家
    paymentMethodCode: ''//支付类型
});
onMounted(() => {
    getNeedList()
})
watch(
    () => props.showPayment,
    () => {
        if (!props.showPayment) return;
        handleProcess()

    })
const handleSure = () => {
    if (props.typeIndex === 1) {
        submitFormParameters()//参数

    } else if (props.typeIndex === 2) {
        submitForm(2)//编辑

    } else {
        submitForm(3)//新增

    }
}
const submitForm = (index) => {
    console.log(form.value);
    // return
    proxy.$refs["payMentRef"].validate((valid) => {
        if (!valid) return
    })
    if (!proxy.publicArray(form.value.paymentWayDescriptionList))
        return proxy.$modal.msgError("请完整填写新增语言");
    if (!form.value.allCountries) {
        newList(form.value.CountryLineList)
    }

    if (index === 3) {
        site.general.payment_wayAdd({
            data: form.value
        }).then((res) => {
            if (res.code === 200) {
                proxy.$modal.msgSuccess(res.message);
                Cancel()
                emits('handleSure')
            }
        })
    } else {
        site.general.payment_wayUpdate({
            pathParams: {
                id: props.publicItem.id
            },
            data: form.value
        }).then(res => {
            if (res.code === 200) {
                proxy.$modal.msgSuccess(res.message);
                Cancel()
                emits('handleSure')
            }
        })

    }

}
const submitFormParameters = () => {//新增支付参数
    if (!parametersList.value.length) return proxy.$modal.msgError("请添加")
    if (!proxy.publicArray(parametersList.value, 1)) return proxy.$modal.msgError("请完整填写")
    order.general.payment_way_parameterSaveorupdate(
        { data: parametersList.value }
    ).then(res => {
        if (res.code === 200) {
            emits('handleSure')
        }
    })
}
const handleProcess = () => {   //1是参数2是编辑3是新增
    if (props.typeIndex === 1) {
        title.value = '参数'
        site.general.payment_way_parameterList({
            data: {
                pageNum: 1,
                pageSize: 50,
                param: {
                    paymentWayId: props.publicItem.id
                }
            }
        }
        ).then(res => {
            parametersList.value = res.data
        })
    } else if (props.typeIndex === 2) {
        title.value = '编辑'
        site.general.payment_wayGetbyid({
            pathParams: {
                id: props.publicItem.id
            }
        }).then(res => {
            form.value.allCountries = res.data?.allCountries
            form.value.environment = res.data?.environment
            form.value.status = res.data?.status
            form.value.newImage = res.data?.iconImageHost
            form.value.paymentMethodCode = res.data?.paymentMethodCode
            form.value.iconImage = res.data?.iconImage
            form.value.paymentWayDescriptionList = res.data?.paymentWayDescriptionList
            form.value.CountryLineList = []
            form.value.CountryLineList = res.data?.paymentWayCountryLineList.map(item => item.countryId)
        })
    } else {
        title.value = '新增'
        form.value.paymentWayDescriptionList = []
        form.value.paymentWayDescriptionList.push({
            languageId: 1,
            name: "",
        });
    }
}

const handleDelete = (index, row) => {
    proxy.$modal.confirm("此操作仅标记删除，点击 “保存” 后才会真正删除，确认要标记此条数据删除吗？").then(() => {
        parametersList.value.splice(index, 1)
        proxy.$modal.msgSuccess('删除成功，请保存');
    })
}

const getNeedList = () => {
    let from = {
        pageNum: 1,
        pageSize: 999,
        param: {},
    };
    product.language.languageList().then((res) => {// 语言列表
        sys_language_type.value = res.data;
    });
    site.country
        .countryList({
            data: from,
        })
        .then((res) => {//国家地区列表
            sys_country.value = res.data;
        });
}
var defaultProps = reactive({
    children: "children",
    label: "description",
    value: "id", // 指定 id 作为 value 属性
});
const handleClose = () => {
    Cancel()
    emits("handleClose")
}
const customization = (e) => {
    console.log(e, '[[[[]]]]');
    if (e) return form.value.CountryLineList = []

}

const Cancel = () => {
    proxy.resetForm("payMentRef");
    form.value.iconImage = ''
    form.value.paymentWayCountryLineList = []

}
const newList = (list) => {
    form.value.paymentWayCountryLineList = []
    list.forEach(e => {
        form.value.paymentWayCountryLineList.push({
            countryId: e,
        })
    });
}


const statusList = reactive([
    {
        label: '开启',
        value: 1
    }, {
        label: '关闭',
        value: 0
    }
])

const handleBaseUrl = (val) => {// 照片的host赋值
    form.value.iconImage = val.url;
};

const publicCheck = (rowList) => {/** 复选框选中数据 */
    checkedBrandDescription.value = rowList;
};
const handleDeleteBrandDescription = () => {/** 多语言删除按钮操作 */
    if (!checkedBrandDescription.value.length) return proxy.$modal.msgError("请先选择要删除的多语言");
    form.value.paymentWayDescriptionList = form.value.paymentWayDescriptionList.filter(
        (item) => !checkedBrandDescription.value.includes(item.index)
    );
    checkedBrandDescription.value = [];
};

const handleAddBrandDescription = () => {/** 多语言添加按钮操作 */
    if (props.typeIndex != 1) {
        form.value.paymentWayDescriptionList.push({
            languageId: null,
            name: "",
        });
    } else {
        parametersList.value.push({
            paymentWayId: props.publicItem.id,
            paymentKey: "",
            paymentValue: ""
        })
    }

};
const rules = {
    CountryLineList: [{ required: true, trigger: "blur", message: "请选择" }],
    environment: [{ required: true, trigger: "blur", message: "请选择" }],
    newImage: [{ required: true, trigger: "blur", message: "请选择" }],
    paymentMethodCode: [{ required: true, trigger: "blur", message: "请选择" }],
};
</script>